﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml;

namespace Fingerbrisk.DataSource.FluentDatasourceInteract.Document
{
    public class DocParser
    {
        private XmlDocument _xmlDocument;
        private StringBuilder _response = null;

        public DocParser()
        {
            _xmlDocument = new XmlDocument();
            _response = new StringBuilder("");
        }

        public void Load(string path)
        {
            _xmlDocument.Load(path);

            var layoutElem = _xmlDocument.SelectSingleNode("/document/view/layout");
            foreach (XmlNode childLayout in layoutElem.ChildNodes)
            {
                ProcessLayout(childLayout);
            }
        }

        public void LoadXml(String xml)
        {
            _xmlDocument.LoadXml(xml);

            var layoutElem = _xmlDocument.SelectSingleNode("/document/view/layout");
            foreach(XmlNode childLayout in layoutElem.ChildNodes)
            {
                ProcessLayout(childLayout);
            }
        }

        public void ProcessLayout(XmlNode view)
        {
            var name = view.Name;

            if (view.Name.Equals("repeater"))
            {
                var itemTemplate = view.SelectSingleNode("./itemTemplate");
                var data = view.SelectSingleNode("./data");
                var queryId = data.Attributes["useQuery"].Value;

                _response.AppendLine("<div style='width: 100%; height: 100%;'>");

                ExecuteQuery(queryId);

                _response.AppendLine("</div>");
            }
        }

        public DataSet ExecuteQuery(String queryId)
        {
            var queryElem = _xmlDocument.SelectSingleNode(String.Format("/document/queryset/query[@id='{0}']", queryId));

            var queryBuilder = new StringBuilder();
            ParseQuery(queryElem, queryBuilder);

            DataTable table = new DataTable("Check");

            return null;
        }

        public void ParseQuery(XmlNode queryElem, StringBuilder queryBuilder)
        {
            var sources = queryElem.SelectSingleNode("./from/sources").ChildNodes;
            var selectFields = queryElem.SelectSingleNode("./from/select").ChildNodes;
            var whereClauseGroups = queryElem.SelectSingleNode("./from/where").ChildNodes;

            queryBuilder.Append("select ");

            foreach (XmlNode field in selectFields)
            {
                queryBuilder.Append(String.Format("{0} as {1} ", field.Attributes["value"].Value, field.Attributes["as"].Value ?? field.Attributes["value"].Value));
            }

            queryBuilder.Append("from ");

            foreach (XmlNode source in sources)
            {
                if (source.Attributes["type"].Value.Equals("query"))
                {
                    queryBuilder.Append("( ");
                    ParseQuery(_xmlDocument.SelectSingleNode(String.Format("/document/queryset/query[@id='{0}']", source.Attributes["queryId"].Value)), queryBuilder);
                    queryBuilder.Append(String.Format(") as {0} ", source.Attributes["alias"].Value ?? source.Attributes["queryId"].Value));
                }
                else if (source.Attributes["type"].Value.Equals("table"))
                {
                    queryBuilder.Append(String.Format(" {0} as {1} ", source.Attributes["name"].Value, source.Attributes["alias"].Value ?? source.Attributes["name"].Value));
                }
            }

            foreach (XmlNode whereClauseGroup in whereClauseGroups)
            {
                var count = 0;
                foreach (XmlNode whereClause in whereClauseGroup.ChildNodes)
                {
                    queryBuilder.Append(String.Format(" where {0} {1} {2} ", whereClause.Attributes["key"].Value, whereClause.Attributes["operator"].Value, whereClause.Attributes["value"].Value));
                    queryBuilder.Append(" ");

                    if (count != whereClauseGroup.ChildNodes.Count - 1)
                        queryBuilder.Append(whereClauseGroup.Attributes["type"].Value);

                    queryBuilder.Append(" ");

                    count++;
                }
            }
        }
    }
}
